package com.wing.tools.screenlive.encoder;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**
 * Created by wejust on 2018/1/4.
 */

public class VideoEncoder extends Thread {
    protected VideoEncodeWorker mWorker;
    protected VideoEncodeWorker.IReceiver mReceiver;
    // video width
    protected int mWidth;
    // video height
    protected int mHeight;
    protected int mTextureID;
    protected int mFrameInterval = 2;
    protected int mVideoBitrate = 1 * 1000 * 1000;
    protected int mFPS = 10;
    protected int mIndex = 0;

    Handler mHandler;
    Looper mLooper;
    boolean mRunning = false;

    public VideoEncoder(VideoEncodeWorker.IReceiver receiver){
        mReceiver = receiver;
    }

    public boolean isRunning(){
        return mRunning;
    }

    public void config(int frameInterval, int videoBitrate, int width , int height, int fps)    {
        this.mFrameInterval = frameInterval;
        this.mVideoBitrate = videoBitrate;
        this.mWidth = width;
        this.mHeight = height;
        this.mFPS = fps;

        mWorker = new VideoEncodeWorker(mReceiver);
        mWorker.init(mWidth, mHeight, mVideoBitrate, mFPS, mFrameInterval);
    }


    @Override
    public void run(){
        mRunning = true;

        Looper.prepare();
        mLooper = Looper.myLooper();

        mHandler = new Handler(){
            public void handleMessage(Message msg)
            {
                onMessage(msg);
            };
        };
        onStart();

        Looper.loop();

        release();

        onEnd();

        mRunning = false;
    }

    protected void onStart(){

    }

    protected void onMessage(Message message){

    }

    protected void onEnd(){

    }

    protected void release(){
        if(mWorker != null){
            mWorker.setIsRunning(false);
            mWorker.release();
            mWorker = null;
        }
    }

    public void begin(){
        mWorker.setIsRunning(true);
        mWorker.start();

        start();
    }

    public void end(){
        mLooper.quit();
    }
}
